import { useState, useEffect } from "react";

interface User {
  id: number;
  username: string;
  roles: string[];
  permissions: string[];
}

// 模拟从localStorage获取用户信息
// const getUserInfo = (): User | null => {
//   const userInfo = localStorage.getItem("userInfo");
//   return userInfo ? JSON.parse(userInfo) : null;
// };

export const useAuth = () => {
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    // 从 localStorage 获取用户信息
    const userInfo = localStorage.getItem("userInfo");
    if (userInfo) {
      setUser(JSON.parse(userInfo));
    }
  }, []);

  const hasPermission = (permission: string) => {
    if (!user) return false;
    return (
      // 超级管理员拥有所有权限
      user.permissions.includes("*") || user.permissions.includes(permission)
    );
  };

  const hasRole = (role: string) => {
    if (!user) return false;
    return user.roles.includes(role);
  };

  const logout = () => {
    localStorage.removeItem("token");
    localStorage.removeItem("userInfo");
    setUser(null);
  };

  return { user, hasPermission, hasRole, logout };
};
